import { director } from "cc";
import { BaseClass } from "../../../Framework/Scripts/Managers/BaseClass";
import { WSRecvDataEvent } from "../../../Framework/Scripts/Managers/Net/NetCfg";
import { GameConfig, Stype } from "../Config/GameCfg";
import { Msg, decodeMsgRes, encodeMsg } from "../../AssetPackage/Props/DT";

/**
 * 网络协议解析类
 */
export class MsgData extends BaseClass {
    //是否是测试数据
    private isTest = !GameConfig.isUseWs;
    
    private static _inst: MsgData;
    public static get inst(): MsgData {
        if (this._inst == null) {
            this._inst = new MsgData();
        }

        return this._inst;
    }

    constructor() {
        super()  
    }

    public Init(): void {
        director.on(WSRecvDataEvent,this.onMsgEvent,this);   
    }


    private stringToBase64(inputString: string): string {
        const encoder = new TextEncoder();
        const data = encoder.encode(inputString);
        const base64String = btoa(String.fromCharCode(...data));
        return base64String;
    }

    /**
     * 
     * @param stype 服务号
     * @param ctype 命令号
     * @param uint8Array 
     */
    public sendDate(stype: number, ctype: number,uint8Array: Uint8Array ){
        let msg:Msg = {
            stype:stype,
            ctype: ctype,
            buffer: uint8Array,
        };
        //编码协议数据
        let buf:Uint8Array = encodeMsg(msg);
        // console.log('======编码协议数据=========',buf);
        // 测试解码
        // let data = decodeMsg(buf);
        // console.log('======编码解码数据======',data);

        //去掉数据编码产生的0
        let str = buf.toString();
        let arr = str.split(',');
        let arr2 = []
        arr.forEach(element => {
            arr2.push(parseInt(element));
        });
        const uint8Array1 = new Uint8Array(arr2);
        // console.log('=========编码协议数据========',uint8Array1);
        console.error('=========sendDate========',stype,ctype);
        let arrbuffer = uint8Array1.buffer;
        // NetMgr.inst.send(arrbuffer);
    }

 




 






    //解析服务收到的消息
    public onMsgEvent(binaryData: any ): void{
        console.warn('========onMsgEvent1========',binaryData);
        let uint8Array:Uint8Array = new Uint8Array(binaryData);
        let decoded = decodeMsgRes(uint8Array);
      
        let stype = decoded.stype;  //服务号
        let ctype = decoded.ctype;  //命令号
        let msg = new Uint8Array(decoded.buffer);   //数据,是buf字符串
        console.warn('========onMsgEvent2========',stype,ctype);
        console.warn('========onMsgEvent3========',msg);
        switch (stype) {
            // case Stype.Auth:
            //    MsgDataLogin.inst.onMsg(ctype,msg);
            //     break;
            // case Stype.Hall:
            //     MsgDataHall.inst.onMsg(ctype,msg);
            //     break;
            // case Stype.Game:
            //     MsgDataGame.inst.onMsg(ctype,msg);
            //     break;
            default:
                break;
        }
    } 
}